package com.onlineclass.backstagemanagement.controller;

import com.onlineclassbackstage.beans.User;
import com.onlineclassbackstage.beans.Role;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;


@RequestMapping("/user")
@Controller
@Api(value = "用户操作")
public class UserController {

    @Autowired
    private RedisTemplate redisTemplate;

    //用户登录,登录成功返回status：1，登录失败返回status：0，info为登录失败，用户名或密码错误。
    @ApiOperation(value = "登录方法",notes = "用户登录,登录成功返回status：1，登录失败返回status：0，info为登录失败，用户名或密码错误。")
    @PostMapping("/login")
    @ResponseBody
    public ModelAndView login(User user, Role role, HttpServletRequest request,HttpServletResponse response) throws UnsupportedEncodingException {
        user.setRole(role);
        request.setCharacterEncoding("UTF-8");

        ModelAndView modelAndView = new ModelAndView();
        try {
            Subject subject = SecurityUtils.getSubject();
            AuthenticationToken authenticationToken = new UsernamePasswordToken(user.getUsername()+":"+user.getRole().getRolename(), user.getPwd());
            subject.login(authenticationToken);
            User u = (User) subject.getPrincipal();
            RedisTemplate<String, User> template = new RedisTemplate<>();
            redisTemplate.opsForValue().set(User.getToken(u),u);
            Cookie cookie = new Cookie("token",User.getToken(u));
            cookie.setPath("/");
            cookie.setDomain("localhost");
            response.addCookie(cookie);
            modelAndView.setViewName("redirect:/static/html/index.html");
        } catch (Exception e) {
            e.printStackTrace();
            modelAndView.setViewName("redirect:/static/errorLogin.html");
        }
        return modelAndView;

    }









}
